<template>
  <div class="container">
    <div class="header">
      <router-link to="/" tag="div" class="header-left">
          <div class="iconfont back-icon">&#xe624;</div>
      </router-link>
      <input  class="header-input"
              type="text"
              placeholder="输入城市或拼音"
              v-model="keyword"/>
        <div class="header-right">
          搜索
        </div>
    </div>
    <search-list v-show="listShow" :list='list'></search-list>
  </div>
</template>

<script>
import axios from 'axios'
import SearchList from './component/List.vue'
import { mapState } from 'vuex'
export default {
  name: 'Search',
  components: {
    SearchList
  },
  data () {
    return {
      listShow: true,
      keyword: '',
      allcity: [],
      newCity: [],
      list: [],
      timer: null
    }
  },
  computed: {
    ...mapState(['city'])
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        this.cityList()
      }, 100)
    }
  },
  methods: {
    getSearchInfo () {
      axios.get('static/city.json')
        .then(this.getSearchInfoSucc)
    },
    getSearchInfoSucc (res) {
      if (res.data) {
        this.allcity = res.data.cities.domestic
      }
    },
    cityList () {
      const result = []
      for (const i in this.allcity) {
        for (const y in this.allcity[i].cities) {
          this.newCity = this.allcity[i].cities[y].city_name
          this.newCity = this.newCity.split(',')
          this.newCity.forEach((value) => {
            if (value.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
      }
      this.list = result
    }
  },
  mounted () {
    this.getSearchInfo()
  }
}
</script>

<style lang="stylus">
  @import '~styles/varibles.styl'
  @import '~styles/mixins.styl'
  .container
    background: $bodybgColor
    .header
      display: flex
      height: $headerHeight
      line-height $headerHeight
      background: #fff
      color: #333
      .header-left
        width: .64rem
        float:left
        .back-icon
          text-align: center
          font-size: .3rem
          font-weight: bold
      .header-input
        flex: 1
        height: .6rem
        line-height .6rem
        color: #333
        background: $bodybgColor
        font-family: Arial,"Microsoft Yahei","Helvetica Neue",Helvetica,sans-serif
        margin-top: .15rem
        margin-left: .1rem
        border-radius: .4rem
        text-align: center
        font-size: .28rem
      .header-right
        width: 1rem
        padding: 0 .1rem
        float:right
        text-align: center
        color: #333
</style>
